import React, { PureComponent, Fragment } from 'react';
import { routerRedux, Route } from 'dva/router';
import { connect } from 'dva';
import {
  Table,
  Divider,
  Form,
  Select,
  Card,
  Button,
  message,
  Modal,
} from 'antd';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import styles from './StructureMaintenance.less';

import process from '../../assets/process.png';

const FormItem = Form.Item;
const ButtonGroup = Button.Group;

const assignType = ['自动', '手动'];
const autoAssign = ['排队模式', '规则模式'];

@connect(({ system }) => ({
  system,
}))
@Form.create()
export default class AllocationRules extends PureComponent {
  state = {
    width: '875px',
    modalVisible: false,
    assignedVisible: false,
    lowChartVisible: false,
    assignedDetails: null,
    assignedList: null,
    rulesDetails: null,
  };

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'system/getRuleTable',
    });
  }

  columns = [
    { title: '序号', dataIndex: 'nodeId', key: 'nodeId' },
    { title: '任务名', dataIndex: 'nodeName', key: 'nodeName' },
    {
      title: '分派类型',
      dataIndex: 'assignType',
      key: 'assignType',
      render(val) {
        return assignType[val - 1];
      },
    },
    { title: '手动分派人', dataIndex: 'name', key: 'name' },
    {
      title: '自动分派方式',
      dataIndex: 'autoAssign',
      key: 'autoAssign',
      render(val) {
        return autoAssign[val - 1];
      },
    },

    {
      title: '操作',
      dataIndex: 'id',
      key: 'id',
      render: (text, record) => (
        <Fragment>
          <a onClick={() => this.handleEdit(record)}>修改</a>
          <Divider type="vertical" />
          <a onClick={() => this.handleAssigned(record)}>人员指派</a>
        </Fragment>
      ),
    },
  ];

  columnsAssigned = [
    {
      title: '姓名',
      dataIndex: 'assigner',
      key: 'assigner',
    },
    {
      title: '角色',
      dataIndex: 'roleName',
      key: 'roleName',
    },
  ];

  handleEdit = record => {
    this.setState({
      modalVisible: true,
      rulesDetails: record,
    });
  };

  handleAssigned = record => {
    const { dispatch } = this.props;
    if (record.assignType == 1) {
      dispatch(routerRedux.push(`task-signed?id=${record.id}&nodeId=${record.nodeId}`));
    } else {
      dispatch({
        type: 'system/getPersonnes',
        payload: {
          nodeId: record.nodeId,
        },
        callback: () => {
          this.setState({
            assignedList: record,
            assignedVisible: true,
          });
        },
      });
    }
  };

  handleAssignedCancel = () => {
    this.setState({
      assignedVisible: false,
    });
  };

  handleAssignedOK = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'system/assignPersonne',
      payload: {
        id: this.state.assignedList.id,
        assigner: this.state.assignedDetails.assignerId,
      },
      callback: () => {
        const { system: { systemResult } } = this.props;
        if (systemResult.code == 200) {
          message.success('提交成功');
          dispatch({
            type: 'system/getRuleTable',
          });
          this.setState({
            assignedVisible: false,
          });
        } else {
          message.error(systemResult.message);
        }
      },
    });
  };

  handleEditRulesCancel = () => {
    this.setState({
      modalVisible: false,
    });
  };

  handleEditRulesOK = () => {
    const { dispatch } = this.props;
    const { validateFieldsAndScroll } = this.props.form;
    validateFieldsAndScroll((error, values) => {
      if (!error) {
        dispatch({
          type: 'system/nodeAssignUpdate',
          payload: {
            id: this.state.rulesDetails.id,
            ...values,
          },
          callback: () => {
            const { system: { systemResult } } = this.props;
            if (systemResult.code == 200) {
              message.success('修改成功');
              dispatch({
                type: 'system/getRuleTable',
              });
              this.setState({
                modalVisible: false,
              });
            } else {
              message.error(systemResult.message);
            }
          },
        });
      }
    });
  };

  handleCustomerSelect = record => {
    this.setState({
      assignedDetails: record,
    });
  };

  handleClickShow = () => {
    this.setState({
      lowChartVisible: true,
    });
  };

  handlelowChartVisibleOK = () => {
    this.setState({
      lowChartVisible: false,
    });
  };

  handlelowChartVisibleCancel = () => {
    this.setState({
      lowChartVisible: false,
    });
  };

  render() {
    const {
      system: { systemRuleList, systemLoading, systemAssignedList, userLoading },
    } = this.props;
    const { getFieldDecorator } = this.props.form;
    const rowSelection = {
      type: 'radio',
      onSelect: this.handleCustomerSelect,
    };

    const action = (
      <div style={{ flex: '1' }}>
        <ButtonGroup>
          <Button onClick={this.handleClickShow}>流程图展示</Button>
        </ButtonGroup>
      </div>
    );

    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
    };

    return (
      <PageHeaderLayout
        title="分配规则制定"
        action={action}
        className={styles.channelDetailsContainer}
      >
        {/* {JSON.stringify(systemRuleList)} */}
        <Card bordered={false}>
          <div className={styles.tableList}>
            <Table
              columns={this.columns}
              dataSource={systemRuleList}
              rowKey="id"
              loading={systemLoading}
            />
          </div>
        </Card>
        <Modal
          title="修改分派规则"
          visible={this.state.modalVisible}
          onCancel={this.handleEditRulesCancel}
          onOk={this.handleEditRulesOK}
          confirmLoading={userLoading}
        >
          <Form>
            <FormItem {...formItemLayout} label="分派类型">
              {getFieldDecorator('assignType', {
                initialValue: this.state.rulesDetails && this.state.rulesDetails.assignType,
                rules: [{ required: true, message: '请输入分派类型' }],
              })(
                <Select placeholder="请选择分派类型" onChange={this.handleChange}>
                  <Option value={1}>自动</Option>
                  <Option value={2}>手动</Option>
                </Select>
              )}
            </FormItem>
            <FormItem {...formItemLayout} label="自动分派方式">
              {getFieldDecorator('autoAssign', {
                initialValue: this.state.rulesDetails && this.state.rulesDetails.autoAssign,
                rules: [{ required: true, message: '请选择分派方式' }],
              })(
                <Select placeholder="请选择分派方式" onChange={this.handleChange}>
                  <Option value={1}>排队模式</Option>
                  <Option value={2}>规则模式</Option>
                  <Option value={3}>创建人自身</Option>
                </Select>
              )}
            </FormItem>
          </Form>
        </Modal>

        <Modal
          title="人员指派"
          visible={this.state.assignedVisible}
          onCancel={this.handleAssignedCancel}
          onOk={this.handleAssignedOK}
          // confirmLoading={}
        >
          <Table
            style={{ marginTop: '10px' }}
            size="small"
            rowKey="id"
            columns={this.columnsAssigned}
            pagination={false}
            loading={userLoading}
            rowSelection={rowSelection}
            dataSource={systemAssignedList}
            // onChange={this.handleStandardTableChange}
          />
        </Modal>
        <Modal
          title="流程图"
          width={this.state.width}
          visible={this.state.lowChartVisible}
          onCancel={this.handlelowChartVisibleCancel}
          onOk={this.handlelowChartVisibleOK}
          // confirmLoading={}
        >
          <img src={process} style={{ width: '850px' }} />
        </Modal>
      </PageHeaderLayout>
    );
  }
}
